package org.example.day04;

/**
 * 第二章节2.2.1:synchronized方法的弊端 (两个线程串行执行长任务)
 */
public class MyThread {
    private String getData1;
    private String getData2;
    public synchronized void LongTask(){
        try {
            System.out.println("begin task");
            Thread.sleep(3000);
            getData1 = "值1  threadName = " + Thread.currentThread().getName();
            getData2 = "值2  threadName = " + Thread.currentThread().getName();
            System.out.println(getData1);
            System.out.println(getData2);
            System.out.println("end task");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread m1 = new MyThread();
        Thread1A ta = new Thread1A(m1);
        ta.start();
        Thread1B tb = new Thread1B(m1);
        tb.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long beginTime = CommonUtils.beginTime1;
        if(CommonUtils.beginTime2 < CommonUtils.beginTime1){
            beginTime = CommonUtils.beginTime2;
        }
        long endTime = CommonUtils.endTime1;
        if(CommonUtils.endTime2 > CommonUtils.endTime1){
            endTime = CommonUtils.endTime2;
        }
        System.out.println("耗时： " + ((endTime - beginTime) /1000));
    }
}

class CommonUtils {
    public static long beginTime1;
    public static long endTime1;
    public static long beginTime2;
    public static long endTime2;
}

class Thread1A extends Thread{
    private MyThread m1;
    public Thread1A(MyThread m1) {
        this.m1 = m1;
    }
    @Override
    public void run() {
        CommonUtils.beginTime1 = System.currentTimeMillis();
        m1.LongTask();
        CommonUtils.endTime1 = System.currentTimeMillis();
    }
}
class Thread1B extends Thread {
    private MyThread m1;
    public Thread1B(MyThread m1) {
        this.m1 = m1;
    }
    @Override
    public void run() {
        CommonUtils.beginTime2 = System.currentTimeMillis();
        m1.LongTask();
        CommonUtils.endTime2 = System.currentTimeMillis();
    }
}